from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.options import Options
from selenium.common.exceptions import TimeoutException
import qrcode
import json
import base64
from PIL import Image
from pyzbar.pyzbar import decode

def save_cookie(driver, filename='jsoncookie.json'):
    """保存cookie到文件"""
    cookie = json.dumps(driver.get_cookies())
    with open(filename, 'w') as f:
        f.write(cookie)
    print(f"Cookie已保存到 {filename}")

def get_and_display_login_qr(driver):
    """获取登录二维码URL并在终端显示"""
    # 获取二维码图片元素
    qr_img = driver.find_element(By.CSS_SELECTOR, ".login-scan-box>div>div>img")
    # 获取图片的src属性，这通常是一个包含实际URL的data URI
    qr_data_uri = qr_img.get_attribute("src")
    
    # 从data URI中提取实际的URL或token
    qr_data = qr_data_uri.split(',')[1]

    # 将二维码图片保存到本地
    with open("image/qrcode.png", "wb") as f:
        f.write(base64.b64decode(qr_data))

    barcode_url = ''
    barcodes = decode(Image.open('image/qrcode.png'))
    for barcode in barcodes:
        barcode_url = barcode.data.decode("utf-8")
    print(barcode_url)
    
    qr = qrcode.QRCode()
    qr.add_data(barcode_url)
    #invert=True白底黑块,有些app不识别黑底白块.
    qr.print_ascii(invert=True)
    
    # 生成 ASCII 艺术形式的 QR 码并打印
    qr.print_ascii(invert=True)
    print("请使用哔哩哔哩 App 扫描上方二维码进行登录")

def wait_for_login(driver, timeout=60):
    """等待登录成功"""
    try:
        WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, ".header-avatar-wrap--container.mini-avatar--init"))
        )
        return True
    except TimeoutException:
        print(f"登录超时，等待了 {timeout} 秒")
        return False

def main():
    # 设置Edge浏览器选项
    options = Options()
    options.add_argument('--headless')  # 无头模式
    
    # 初始化WebDriver
    driver = webdriver.Edge(options=options)
    driver.get('https://www.bilibili.com/')
    driver.implicitly_wait(10)

    try:
        # 查找登录按钮
        login_tag = driver.find_elements(By.CSS_SELECTOR, ".header-login-entry")
        if login_tag:
            login_tag[0].click()
            # 获取并在终端显示登录二维码
            get_and_display_login_qr(driver)
            
            print("等待登录成功，最多等待60秒...")

            # 等待登录成功
            if wait_for_login(driver):
                print("登录成功")
                # 保存cookie
                save_cookie(driver)
            else:
                print("登录失败或超时")
        else:
            print("未找到登录按钮，可能已经登录")
    finally:
        # 关闭浏览器
        driver.quit()

if __name__ == "__main__":
    main()
    
    
    